//
//  MTUserForgetViewController.swift
//  MT
//
//  Created by ooops on 2020/4/4.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition

class MTUserForgetViewController: BaseViewController {
    
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        .backgroundStyleTransparent
    }
    
    override func yp_navigationBarTintColor() -> UIColor! {
        UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigationBackgroundColor() -> UIColor! {
        .clear
    }

    override func yp_navigationBackgroundImage(withIdentifier identifier: AutoreleasingUnsafeMutablePointer<NSString?>!) -> UIImage! {
        return nil
    }
    
    private lazy var provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    
    /// 账号 TextField
    var accTextField: UITextField?
    /// 邮箱 TextField
    //var emailTextField: UITextField?
    
    /// 登录按钮
    lazy var forgetPasswordButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.theme.main
        btn.setTitle("找回密码", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 22
        btn.addTarget(self, action: #selector(MTUserForgetViewController.ValidateData), for: .touchUpInside)
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    

    private func setupUI() {
        let accTF = createTextField(withPlaceholder: "请输入要找回的邮箱账号")
        self.accTextField = accTF
        //self.accTextField?.text = "348043793@qq.com"
        
//        let emailTF = createTextField(withPlaceholder: "请输入邮箱")
//        emailTF.isSecureTextEntry = true
//        self.emailTextField = emailTF
        
        self.view.addSubview(accTF)
//        self.view.addSubview(emailTF)
        self.view.addSubview(forgetPasswordButton)
        
        accTF.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(70)
            make.right.equalTo(self.view).offset(-70)
            make.top.equalTo(self.view.snp.centerY)
            make.height.equalTo(30)
        }
        
//        emailTF.snp.makeConstraints { (make) in
//            make.left.right.height.equalTo(accTF)
//            make.top.equalTo(accTF.snp.bottom).offset(30)
//        }
        
        forgetPasswordButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 124)
            make.centerX.equalTo(view)
            make.width.equalTo(210)
            make.height.equalTo(44)
        }
        
    }
    
    @objc private func forgetUserPassword(account: String) {
        
        let parameter: [String : Any] = ["userName" : account]
        MBProgressHUD_JChat.showLoading(self.view)
        provider.originRequest(.forgetPassword(parameter: parameter), callbackQueue: .global(), progress: nil) { [weak self] (result, _) in
            guard let weakSelf = self else { return }
            switch result {
            case .success(let response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    DispatchQueue.main.async {
                        MBProgressHUD_JChat.dismiss(weakSelf.view)
                    }
                    if code == 200 {
                        DispatchQueue.main.async {
                            AlertManager.presentAlertView(message: "重置密码的邮件已发送至您的邮箱")
                            DispatchQueue.main.after(2) {
                                weakSelf.navigationController?.popToRootViewController(animated: true)
                            }
                        }
                    } else {
                        DispatchQueue.main.async {
                            AlertManager.presentAlertView(message: datas["message"] as? String ?? "重置密码失败, 请稍后重试")
                        }
                    }
                }
                break
            case let .failure(error):
                DispatchQueue.main.async {
                    MBProgressHUD_JChat.dismiss(weakSelf.view)
                    AlertManager.presentAlertView(message: error.localizedDescription)
                }
                break
            }
        }
        
    }
    
    /// 检查数据合法性
    @objc private func ValidateData() {
        
        /// 检查邮件合法
        if let acc = self.accTextField?.text {
            if !isValidEmail(testStr: acc) {
                DispatchQueue.main.async {
                    AlertManager.presentAlertView(message: "请输入正确的邮箱")
                }
                return
            }
            self.forgetUserPassword(account: acc)
        } else {
            DispatchQueue.main.async {
                AlertManager.presentAlertView(message: "请输入正确的邮箱")
            }
            return
        }
    }
    
    func isValidEmail(testStr:String) -> Bool {
        // debugPrint("validate calendar: \(testStr)")
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"

        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: testStr)
    }
    
    private func createTextField(withPlaceholder placeholder: String) -> UITextField {
        let tf = UITextField()
        tf.font = PingFangSCRegularFont(14)
        tf.textColor = .black
        tf.tintColor = .black
        
        let astr = NSMutableAttributedString(string: placeholder)
        astr.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.black.withAlphaComponent(0.8)], range: NSMakeRange(0, astr.length))
        tf.attributedPlaceholder = astr
        tf.textAlignment = .center
        
        let line = UIView()
        line.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        tf.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(tf)
            make.height.equalTo(0.5)
        }
        return tf
    }

}
